//得到当前控制器的名称
function get_current_controller_name() {
    return $("#current_controller_name").val();
}

//得到当前控制器action的名称
function get_current_action_name() {
    return $("#current_action_name").val();
}


//获取联盟商id
function get_current_userinfo_id() {
    return sessionStorage.userinfo_id;
}

//获取微信业务id
function get_current_business_id() {
    return sessionStorage.business_id;
}


//获取小Cid
function get_current_customer_id() {
    return sessionStorage.customer_id;
}

//获取小C手机号码
function get_current_customer_mobile() {
    return sessionStorage.customer_mobile;
}


//微信提示弹出框
//title 标题
//content 内容
//confirm_content 确定按钮渲染内容（ 可选）
//confirm_callback 确定按钮回调（ 可选）
function jyd_dialog_alert(options) {

    var title = options.title;
    var content = options.content;
    var confirm_callback = options.confirm_callback;
    var confirm_content = options.confirm_content == null ? '确定' : options.confirm_content;

    //移除事件
    $('#jyd_weui_dialog_alert .weui_dialog_ft .primary').unbind("click");

    if (confirm_content != null) {
        $('#jyd_weui_dialog_confirm .weui_dialog_ft .primary').html(confirm_content);
    }

    $("#jyd_weui_dialog_alert .weui_dialog_title").html(title);
    $("#jyd_weui_dialog_alert .weui_dialog_bd").html(content);

    $("#jyd_weui_dialog_alert .weui_dialog_ft .primary").click(function () {
        if (typeof(confirm_callback) == "function") {
            confirm_callback();
        }
        console.log('点击确定按钮');
        $("#jyd_weui_dialog_alert").hide();
    })
    $("#jyd_weui_dialog_alert").show();
}


//微信确认弹出框
//title 标题
//content 内容
//cancel_content 取消按钮渲染内容（ 可选）
//cancel_callback 取消按钮回调（ 可选）
//confirm_content 确定按钮渲染内容（ 可选）
//confirm_callback 确定按钮回调（ 可选）
function jyd_dialog_confirm(options) {

    var title = options.title == null ? '提示信息' : options.title;
    var content = options.content;
    var cancel_content = options.cancel_content == null ? '取消' : options.cancel_content;
    var confirm_content = options.confirm_content == null ? '确定' : options.confirm_content;
    var cancel_callback = options.cancel_callback;
    var confirm_callback = options.confirm_callback;

    //移除事件
    $('#jyd_weui_dialog_confirm .weui_dialog_ft .primary').unbind("click");
    $('#jyd_weui_dialog_confirm .weui_dialog_ft .default').unbind("click");


    $("#jyd_weui_dialog_confirm .weui_dialog_title").html(title);
    $("#jyd_weui_dialog_confirm .weui_dialog_bd").html(content);

    if (cancel_content != null) {
        $('#jyd_weui_dialog_confirm .weui_dialog_ft .default').html(cancel_content);
    }
    if (confirm_content != null) {
        $('#jyd_weui_dialog_confirm .weui_dialog_ft .primary').html(confirm_content);
    }

    $("#jyd_weui_dialog_confirm .weui_dialog_ft .default").click(function () {

        if (typeof(cancel_callback) == "function") {
            cancel_callback();
        }
        console.log('点击取消按钮');
        $("#jyd_weui_dialog_confirm").hide();
    })

    $("#jyd_weui_dialog_confirm .weui_dialog_ft .primary").click(function () {
        if (typeof(confirm_callback) == "function") {
            confirm_callback();
        }
        console.log('点击确定按钮');
        $("#jyd_weui_dialog_confirm").hide();
    })
    $("#jyd_weui_dialog_confirm").show();
}


//微信toast
//content 提示内容
//stay_times 持续时间 （ 可选）默认为1000ms
function jyd_toast(options) {

    var content = options.content;
    var stay_times = typeof(options.stay_times) == "number" ? options.stay_times : 1000;

    $("#toast .weui_toast_content").html(content);
    $("#toast").show();
    setTimeout(function () {
        $("#toast").hide();
    }, stay_times);
}


//微信加载toast
//content 提示内容
function jyd_loading_toast(options) {

    var content = options.content;
    $("#loadingToast .weui_toast_content").html(content);
    $("#loadingToast").show();
}

//微信加载toast消失
function jyd_loading_toast_hide() {
    console.log('微信加载toast消失');
    $("#loadingToast").hide();
}


//微信上拉菜单
//menu_list 菜单列表{'content':内容,'callback': 回调函数}
//cancel_content 取消按钮内容(可选)，默认为取消
//cancel_callback 取消按钮回调(可选)，默认为取消
function jyd_actionsheet(options) {

    console.log('上拉菜单初始化!');
    var menu_list = typeof(options.menu_list) == "object" && options.menu_list.length > 0 ? options.menu_list : [];
    var cancel_content = options.cancel_content != null ? options.cancel_content : '取消';
    var cancel_callback = options.cancel_callback;

    //移除事件
    $("#actionSheet_wrap .weui_actionsheet_cell").unbind("click");
    $("#actionSheet_wrap #mask").removeClass('weui_fade_toggle');
    $("#actionSheet_wrap #weui_actionsheet").removeClass('weui_actionsheet_toggle');
    $("#actionSheet_wrap .weui_actionsheet_menu").html('');

    var i = 1;
    menu_list.forEach(function (menu) {
        $("#actionSheet_wrap .weui_actionsheet_menu").append("<div class='weui_actionsheet_cell' id='weui_actionsheet_cell" + i + "'>" + menu.content + "</div>");

        $("#actionSheet_wrap .weui_actionsheet_menu #weui_actionsheet_cell" + i).click(function () {
            console.log($(this).text() + "，被点击");
            if (typeof(menu.callback) == "function") {
                menu.callback();
            }
        });
        i++;
    });

    $("#actionSheet_wrap #actionsheet_cancel").click(function () {
        console.log($(this).text() + "，被点击");
        if (typeof(cancel_callback) == "function") {
            cancel_callback();
        }

        $("#actionSheet_wrap #mask").removeClass('weui_fade_toggle');
        $("#actionSheet_wrap #weui_actionsheet").removeClass('weui_actionsheet_toggle');
    });

    $("#actionSheet_wrap #mask").addClass('weui_fade_toggle');
    $("#actionSheet_wrap #weui_actionsheet").addClass('weui_actionsheet_toggle');
}


//添加购物车
function add_product_to_cart(product_id, number) {

    jyd_loading_toast({content: ""});

    var customer_id = (get_current_customer_id()=="") ? get_current_business_id() : get_current_customer_id();

    var req_url = "/elephant_services/get_data?service_path=v2,shopping_cart,update&op=add&userinfo_id=" + get_current_userinfo_id() + "&customer_id=" + customer_id + "&product_id=" + product_id + "&number=" + number;
    //各门店有效订单量
    $.get(req_url, function (data, status) {
        jyd_loading_toast_hide();
        console.log(JSON.stringify(data));
        if (data.flag == 1) {

            update_index_shoppingcart_number(number);
            jyd_toast({"content": "添加成功！", "stay_times": 500});
        } else {
            jyd_toast({"content": "添加失败！", "stay_times": 500});
        }
    });
}


//更新主页购物车气泡数量
function update_index_shoppingcart_number(number){

    var controller_name = get_current_controller_name();
    var action_name = get_current_action_name();

    if(controller_name=="root"){

        update_air_number("index-product-number",number);


        //var current_number = $("#index-product-number").text().replace(/\s/g,"");
        //console.log("更新购物车总数量执行，current_number："+current_number+"，number:"+number);
        //var change_number = number;
        //if(/^\d+$/.test(current_number)){
        //    change_number = parseInt(current_number)+parseInt(number);
        //}
        //
        //console.log("更新购物车总数量执行，current_number："+current_number+"，number:"+number+",change_number"+change_number);
        //
        //if(/^\d+$/.test(change_number+"") && change_number!=0){
        //
        //    $("#index-product-number").html(change_number);
        //    $("#index-product-number").show();
        //}else{
        //    $("#index-product-number").html(0);
        //    $("#index-product-number").hide();
        //}
    }else if(controller_name=="carousels"){
        update_air_number("shoppingcart_air_number",number);
    }

}

//更新购物车气泡数量
//air_number_id 气泡元素的id
//update_number 更新的数字
function update_air_number(air_number_id,update_number){

    var current_number = $("#"+air_number_id).text().replace(/\s/g,"");

    var change_number = update_number;
    if(/^\d+$/.test(current_number)){
        change_number = parseInt(current_number)+parseInt(update_number);
    }

    console.log("更新购物车总数量执行，current_number："+current_number+"，number:"+update_number+",change_number"+change_number);

    update_air_full_number(air_number_id,change_number);
}

//更新购物车气泡总数量
//air_number_id 气泡元素的id
//update_number 更新的数字
function update_air_full_number(air_number_id,update_number){

    if(/^\d+$/.test(update_number+"") && update_number!=0){

        $("#"+air_number_id).html(update_number);
        $("#"+air_number_id).show();
    }else{
        $("#"+air_number_id).html(0);
        $("#"+air_number_id).hide();
    }
}


//遮罩层监听初始化
function mask_listener_event_init(){

    //阻止遮罩层下拉，底层页面滚动
    $('.mask_container').on('touchmove',function(e) {
        //var _x=e.touches[0].pageX;
        //var _y=e.touches[0].pageY;
        //console.log("遮罩层滑动监听："+ e.type);
        e.preventDefault();
    });


    $('.mask_container').children().on('touchmove',function(e) {
        //var _x=e.touches[0].pageX;
        //var _y=e.touches[0].pageY;
        console.log("遮罩层子元素滑动监听："+ e.type+",clientX:"+ e.clientX+",clientY:"+ e.clientY+",screenX"+ e.screenX+",screenY"+ e.screenY+",.touches"+ e.touches);
        e.stopPropagation();
    });
}


$(function(){
    mask_listener_event_init();

    var shared_title = $("#jyd_shared_title").val();
    var shared_desc = $("#jyd_shared_desc").val();
    var shared_url = $("#jyd_shared_url").val();
    var shared_img_url = $("#jyd_shared_img_url").val();
    shared_title = (typeof(shared_title)=="string"&&shared_title!="") ? shared_title : '酒运达';
    shared_desc = (typeof(shared_desc)=="string"&&shared_desc!="") ? shared_desc : '酒运达即可达';
    shared_url = (typeof(shared_url)=="string"&&shared_url!="") ? url_trancation(shared_url) : location.origin;
    shared_img_url = (typeof(shared_img_url)=="string"&&shared_img_url!="") ? url_trancation(shared_img_url) : (location.origin+"/root/jyd_logo.png")

    shared_init(shared_title,shared_desc,shared_url,shared_img_url);
});

function url_trancation(url){

    if(!/^http:\/\/.+/.test(url)){
        url = location.origin+url;
    }
    return url;
}


//商品详情
function product_show(product_id){

    jyd_loading_toast({'content':''});
    location.href = "/product_show?product_id="+product_id;
}




//购物车页面点击
function cart_click(){

    jyd_loading_toast({'content':'处理中……'});
    var customer_id = (get_current_customer_id()=="") ? get_current_business_id() : get_current_customer_id();
    //设置购物车数据
    var req_url = "/elephant_services/get_data?service_path=v2,shopping_cart,products&userinfo_id=" + get_current_userinfo_id() + "&customer_id=" + customer_id;
    //各门店有效订单量
    $.get(req_url, function (data, status) {
        //console.log(JSON.stringify(data));

        //移除之前的元素
        $("#product-cell-model").nextAll().remove();

        var products = [];
        products = products.concat(data.group_purchase_products).concat(data.normal_products);
        products.forEach(function(product){
            console.log("id:"+product.id+",title:"+product.title+",price:"+product.price+",number:"+product.number);
            var model = $("#product-cell-model").clone();
            model.find(".title").html(product.title);
            model.find(".price").html("¥ "+product.price);
            model.find(".number").html(product.number);
            model.find("[name='product_id']").val(product.id);
            model.find("[name='product_number']").val(product.number);
            model.find("[name='product_price']").val(product.price);
            model.show();
            $("#inner-op").append(model);
        });

        shopping_number_cost_reload();
        cart_number_lister();
        jyd_loading_toast_hide();

    });


    if($("#shoppingcart-container").css("display")=='none'){
        $("#shoppingcart-container").show();
    }else{
        $("#shoppingcart-container").hide();
    }

}

//购物车数量监听
function cart_number_lister(){

    //移除之前的监听
    $("#inner-op .reduce").unbind("click");
    $("#inner-op .add").unbind("click");
    //减少购买数量
    $("#inner-op .reduce").click(function(){
        console.log("购物车数量减少！");
        jyd_loading_toast({'content':'处理中'});
        var shoppingcart_cell = $(this).parent().parent();
        var product_id = shoppingcart_cell.find("[name='product_id']").val();
        var customer_id = (get_current_customer_id()=="") ? get_current_business_id() : get_current_customer_id();
        var req_url = "/elephant_services/get_data?service_path=v2,shopping_cart,update&op=reduce&userinfo_id=" + get_current_userinfo_id() + "&customer_id=" + customer_id + "&product_id=" + product_id + "&number=" + 1;
        $.get(req_url, function (data, status) {
            console.log("购物车："+JSON.stringify(data));
            jyd_loading_toast_hide();
            if (data.flag == 1) {
                if(data.number<=0){
                    shoppingcart_cell.remove();
                }else{
                    shoppingcart_cell.find(".number").html(data.number);
                    shoppingcart_cell.find("[name='product_number']").val(data.number);
                }
            } else {
                jyd_toast({"content": "添加失败！", "stay_times": 500});
            }
            shopping_number_cost_reload();
        });
    });

    //增加购买数量
    $("#inner-op .add").click(function(){
        jyd_loading_toast({'content':'处理中'});
        var shoppingcart_cell = $(this).parent().parent();
        var product_id = shoppingcart_cell.find("[name='product_id']").val();
        var customer_id = (get_current_customer_id()=="") ? get_current_business_id() : get_current_customer_id();
        var req_url = "/elephant_services/get_data?service_path=v2,shopping_cart,update&op=add&userinfo_id=" + get_current_userinfo_id() + "&customer_id=" + customer_id + "&product_id=" + product_id + "&number=" + 1;
        //各门店有效订单量
        $.get(req_url, function (data, status) {
            jyd_loading_toast_hide();
            if (data.flag == 1) {
                shoppingcart_cell.find(".number").html(data.number);
                shoppingcart_cell.find("[name='product_number']").val(data.number);
            } else {
                jyd_toast({"content": "添加失败！", "stay_times": 500});
            }
            shopping_number_cost_reload();
        });
    });
}

function shopping_number_cost_reload(){

    var shopping_number = 0;//购物车数量
    var shopping_cost = 0;//购物车金额
    $("#inner-op .product-cell").each(function(){

        var number = $(this).find("[name='product_number']").val();
        var price = $(this).find("[name='product_price']").val();

        if(number=="" || price=="" ) return;
        shopping_number += parseInt(number);
        shopping_cost += parseFloat(price)*parseInt(number);
    });
    $("#shoppingcart-container .product-info .product-head .product-number").html(shopping_number);
    $("#shoppingcart-container .pay-container .paycost").html("合计 ¥ "+shopping_cost.toFixed(2));



    //更新主页购物车数量
    update_air_full_number("index-product-number",shopping_number)
    update_air_full_number("shoppingcart_air_number",shopping_number)


}


//购物车点击冒泡
function shoppingcart_listener_event_init(){

    $("#shoppingcart-container").click(function(){
        console.log("购物车遮罩层点击！");
        $(this).hide();
    });

    $("#shoppingcart-container #inner-op").click(function(event){
        event.stopPropagation();
        console.log("购物车操作层点击！");
    });

    $("#shoppingcart-container .pay-container").click(function(event){
        event.stopPropagation();
        console.log("购物车底部按钮点击！");
    });
}


function go_index(){
    jyd_loading_toast({'content':'加载中……'});
    location.href = '/?f='+Math.random();
    jyd_loading_toast_hide();
}


function go_order(){
    jyd_loading_toast({'content':'加载中……'});
    location.href = '/order/index?f='+Math.random();
    jyd_loading_toast_hide();
}


function shared_init(title,desc,link_url,img_url){

    console.log("js sdk 回调执行！");

    wx.ready(function(){

        console.log("js sdk 回调成功！");
        wx.onMenuShareTimeline({
            title: title, // 分享标题
            link: link_url, // 分享链接
            imgUrl: img_url, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
                console.log("朋友圈分享成功！");
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                console.log("朋友圈分享失败！");
            }
        });


        wx.onMenuShareAppMessage({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link_url, // 分享链接
            imgUrl: img_url, // 分享图标
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                console.log("朋友分享失败！");
            }
        });


        wx.onMenuShareQQ({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link_url, // 分享链接
            imgUrl: img_url, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                console.log("qq分享失败！");
            }
        });

        wx.onMenuShareWeibo({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link_url, // 分享链接
            imgUrl: img_url, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                console.log("qq微博分享失败！");
            }
        });

        wx.onMenuShareQZone({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link_url, // 分享链接
            imgUrl: img_url, // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                console.log("qq空间分享失败！");
            }
        });
    });
    wx.error(function(res){

        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });
}


//刷新定位
function refresh_location(){


    //提示框
    jyd_loading_toast({'content':'正在定位'});

    wx.ready(function(){
        wx.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {

                console.log("定位成功，即将跳转商城主页面！");
                var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                var speed = res.speed; // 速度，以米/每秒计
                var accuracy = res.accuracy; // 位置精度

                location.href = "/get_location?latitude="+latitude+"&longitude="+longitude;
            },
            fail: function(){

                //jyd_toast({content: "默认定位失败！"});

                console.log("定位失败，启动百度网页浏览器定位！");

                var geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition(function(r){
                    if(this.getStatus() == BMAP_STATUS_SUCCESS){
                        jyd_toast({content: "百度定位成功！"});
                        console.log("百度定位成功！您的位置："+r.point.lng+","+r.point.lat);
                        location.href = "/get_location?latitude="+r.point.lat+"&longitude="+r.point.lng;
                    }else {

                        console.log("百度定位失败！status："+this.getStatus());
                    }
                },{enableHighAccuracy: true})
            }
        });
    });
    wx.error(function(res){

        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });
}